<?php
function in_array_2d($needle, $haystack) {
  foreach ($haystack as $value) {
    if (in_array($needle, $value)) {
      return TRUE;
    }
  }
  return FALSE;
}

function seconds_to_days($seconds) {
  $time_in_days = "";
  $negate = "";
  $minutes = 60;
  $hours = 60 * $minutes;
  $days = 24 * $hours;

  if ($seconds < 0){
    $seconds *= -1;
    $negate = "-";
  }
  
  $d = $h = $m = $s = 0;

  $d = floor($seconds/$days);
  $h = floor(($seconds%$days)/$hours);
  $m = floor(((($seconds%$days)%$hours))/$minutes);
  $s = ((($seconds%$days)%$hours)%$minutes);

  if ($d != 0) { $time_in_days .= $d." day(s) "; }
  if ($h != 0) { $time_in_days .= $h." hours(s) "; }
  if ($m != 0) { $time_in_days .= $m." minutes(s) "; }
  if ($s != 0) { $time_in_days .= $s." seconds(s) "; }

  return $negate.$time_in_days;
}

function bag_operation($db, $action, $pid) {

  $errormsg = "";
  $bagUnique = array_unique($_SESSION['shoppingBag']);
  $bagCount = array_count_values($_SESSION['shoppingBag']);

  if (isset($action) && isset($pid)) {
    //construct SELECT query
    $cols = array(0);
    $query = $db->db_select("product", $cols, NULL);
    //execute SELECT query
    $result = $db->database->query($query);
    //result SELECT query
    $tmpProdId = $result->fetchAll(SQLITE_ASSOC);

    if (in_array_2d($pid, $tmpProdId)) {
      //construct SELECT query
      $cols = array(3);
      $conds = array();
      $conds[] = array(0);//col
      $conds[] = array(0);//operator
      $conds[] = array($pid);//value
      $query = $db->db_select("product", $cols, $conds);
      //execute SELECT query
      $result = $db->database->query($query);
      //result SELECT query
      $tmpProd = $result->fetchAll(SQLITE_ASSOC);

      if ($tmpProd[0]['product_quantity'] > 0) {
        if ($action == "inc") {
          if (in_array($pid, $bagUnique)) {
            if (($bagCount[$pid]+1) <= $tmpProd[0]['product_quantity']) {
              array_push($_SESSION['shoppingBag'], $pid);
            } else {
              //printAlert("error", "Oh snap!", "Maximum quantity reached.", $_SERVER['PHP_SELF']);
              $errormsg = "Maximum quantity reached.";
            }
          } else {
            //printAlert("error", "Oh snap!", "Product not in Bag.", $_SERVER['PHP_SELF']);
            $errormsg = "Product not in Bag.";
          }
        }
        if ($action == "dec") {
          if (in_array($pid, $bagUnique)) {
            if (($bagCount[$pid]-1) > 0) {
              $_SESSION['shoppingBag'] = array_diff($_SESSION['shoppingBag'], array($_GET["pid"]));
              for($i = 0; $i < ($bagCount[$pid]-1); $i++) {
                array_push($_SESSION['shoppingBag'], $pid);
              }
            } else {
              //printAlert("error", "Oh snap!", "Minimum quantity reached.", $_SERVER['PHP_SELF']);
              $errormsg = "Minimum quantity reached.";
            }
          } else {
            //printAlert("error", "Oh snap!", "Product not in Bag.", $_SERVER['PHP_SELF']);
            $errormsg = "Product not in Bag.";
          }
        }
        if ($action == "rem") {
          if (in_array($pid, $bagUnique)) {
            $_SESSION['shoppingBag'] = array_diff($_SESSION['shoppingBag'], array($pid));
          } else {
            //printAlert("error", "Oh snap!", "Product not in Bag.", $_SERVER['PHP_SELF']);
            $errormsg = "Product not in Bag.";
          }
        }
        if ($action == "add") {
          if (!in_array($pid, $bagUnique)) {
            array_push($_SESSION['shoppingBag'], $pid);
          } else {
            //printAlert("error", "Oh snap!", "Product already in Bag.", $_SERVER['PHP_SELF']);
            $errormsg = "Product already in Bag.";
          }
        }
      } else {
        //printAlert("error", "Oh snap!", "Product is not available.", $_SERVER['PHP_SELF']);
        $errormsg = "Product is not available.";
      }
    } else {
      //printAlert("error", "Oh snap!", "Invalid Product.", $_SERVER['PHP_SELF']);
      $errormsg = "Invalid Product.";
    }
  }

  return $errormsg;
}

function bag_construction($db) {

  $bagProd = array();
  $bagUnique = array_unique($_SESSION['shoppingBag']);
  $bagCount = array_count_values($_SESSION['shoppingBag']);

  foreach($bagUnique as $value) {
    //construct SELECT query
    $cols = array(0, 1, 3, 4, 5);
    $conds = array();
    $conds[] = array(0);//col
    $conds[] = array(0);//operator
    $conds[] = array($value);//value
    $query = $db->db_select("product", $cols, $conds);
    //execute SELECT query
    $result = $db->database->query($query);
    //result SELECT query
    $tmpProd = $result->fetchAll(SQLITE_ASSOC);
    //construct SELECT query
    $cols = array(1);
    $conds = array();
    $conds[] = array(0);//col
    $conds[] = array(0);//operator
    $conds[] = array($tmpProd[0]['picture_id']);//value
    $query = $db->db_select("picture", $cols, $conds);
    //execute SELECT query
    $result = $db->database->query($query);
    //result SELECT query
    $tmpPic = $result->fetchAll(SQLITE_ASSOC);

    if (empty($tmpProd)) {
      $_SESSION['shoppingBag'] = array_diff($_SESSION['shoppingBag'], array($value));
    } else {
      if ($tmpProd[0]['product_quantity'] <= 0) {
        $_SESSION['shoppingBag'] = array_diff($_SESSION['shoppingBag'], array($value));
      } else {
        if ($tmpProd[0]['product_quantity'] < $bagCount[$tmpProd[0]['product_id']]) {
          $_SESSION['shoppingBag'] = array_diff($_SESSION['shoppingBag'], array($value));
          for($i = 0; $i < $tmpProd[0]['product_quantity']; $i++) {
            array_push($_SESSION['shoppingBag'], $tmpProd[0]['product_id']);
          }
        }
        $tmpProd[0]['picture_name'] = $tmpPic[0]['picture_name'];
        $bagProd[] = $tmpProd[0];
      }
    }
  }

  return $bagProd;
}

function navlist_construction($db) {
  $navlist = array();
  
  //construct SELECT query
  $conds = array();
  $conds[] = array(2); //$param_col;
  $conds[] = array(6); //$param_op;
  $conds[] = array("yes"); //$param_key;
  $query = $db->db_select("list", NULL, $conds);
  //execute SELECT query
  $result = $db->database->query($query);
  //result SELECT query
  $resList = $result->fetchAll(SQLITE_ASSOC);
  
  foreach ($resList as $list) {
    $navcat = array();
    
    //construct SELECT query
    $cols = array();
    $cols = array(1); //$param_col;
    $conds = array();
    $conds[] = array(2); //$param_col;
    $conds[] = array(0); //$param_op;
    $conds[] = array($list['list_id']); //$param_key;
    $query = $db->db_select("category2list", $cols, $conds);
    //execute SELECT query
    $result = $db->database->query($query);
    //result SELECT query
    $resCat2List = $result->fetchAll(SQLITE_ASSOC);
    
    $navcat[] = $list['list_name'];
    
    foreach ($resCat2List as $cat2list) {
      //construct SELECT query
      $cols = array();
      $cols = array(1); //$param_col;
      $conds = array();
      $conds[] = array(0); //$param_col;
      $conds[] = array(0); //$param_op;
      $conds[] = array($cat2list['category_id']); //$param_key;
      $query = $db->db_select("category", $cols, $conds);
      //execute SELECT query
      $result = $db->database->query($query);
      //result SELECT query
      $resCat = $result->fetchAll(SQLITE_ASSOC);
      
      $navcat[] = $resCat[0]['category_name'];
    }
    
    $navlist[$list['list_id']] = $navcat;
  }
  
  return $navlist;
}

function check_expire_deal($db, $bill_id=0) {

  $revert_product = TRUE;
  $update_bill = TRUE;

  $billIds = array();
  $dealIds = array();

  // validate bill
  if ($bill_id == 0) {
    //construct SELECT query
    $cols = array();
    $cols = array(0, 1, 2, 15);
    $conds = array();
    $conds[] = array(3);
    $conds[] = array(6);
    $conds[] = array("new");
    $query = $db->db_select("bill", $cols, $conds);
    $queries[] .= $query.";";
    //execute SELECT query
    $result = $db->database->query($query);
    //result SELECT query
    $tmpBill = $result->fetchAll(SQLITE_ASSOC);

    if (empty($tmpBill)) {
      return FALSE;
    }

    $now = time();
    foreach ($tmpBill as $bill) {
      $cutoff = $bill['bill_timestamp'] + $bill['bill_period'];
      if ($cutoff < $now) {
        $billIds[] = $bill['bill_id'];
        $dealIds[] = $bill['deal_id'];
      }
    }
  } else {
    //construct SELECT query
    $cols = array();
    $cols = array(0, 1, 2, 15);
    $conds = array();
    $conds[] = array(0, 3);
    $conds[] = array(0, 6);
    $conds[] = array($bill_id, "new");
    $query = $db->db_select("bill", $cols, $conds);
    $queries[] .= $query.";";
    //execute SELECT query
    $result = $db->database->query($query);
    //result SELECT query
    $tmpBill = $result->fetchAll(SQLITE_ASSOC);

    if (empty($tmpBill)) {
      return FALSE;
    }

    $now = time();
    $cutoff = $tmpBill[0]['bill_timestamp'] + $tmpBill[0]['bill_period'];
    if ($cutoff < $now) {
      $billIds[] = $tmpBill[0]['bill_id'];
      $dealIds[] = $tmpBill[0]['deal_id'];
    }
  }

  //revert product quantity
  for ($i=0; $i<count($dealIds); $i++) {
    //Get Deal
    $cols = NULL;
    $conds = array();
    $conds[] = array(0);
    $conds[] = array(0);
    $conds[] = array($dealIds[$i]);
    $query = $db->db_select("deal", $cols, $conds);
    $queries[] .= $query.";";
    $result = $db->database->query($query);
    $tmpDeal = $result->fetchAll(SQLITE_ASSOC);

    //Get Product2Deal
    $cols = NULL;
    $conds = array();
    $conds[] = array(2);
    $conds[] = array(0);
    $conds[] = array($tmpDeal[0]['deal_id']);
    $query = $db->db_select("product2deal", $cols, $conds);
    $queries[] .= $query.";";
    $result = $db->database->query($query);
    $tmpProd2Deal = $result->fetchAll(SQLITE_ASSOC);

    //Construct Temp BAG
    $prodIds = array();
    foreach ($tmpProd2Deal as $value) {
      $prodIds[] = $value["product_id"];
    }
    sort($prodIds);
    $prodIdsUnique = array_unique($prodIds);
    $prodIdsCount = array_count_values($prodIds);

    //Construct Temp PRODUCT
    $prodIdsUniqueStr = implode(",", $prodIdsUnique);
    $query = "SELECT * FROM product WHERE product_id in (".$prodIdsUniqueStr.")";
    $queries[] .= $query.";";
    $result = $db->database->query($query);
    $tmpProd = $result->fetchAll(SQLITE_ASSOC);

    //REVERT Product_quantity
    foreach($tmpProd as $value) {
      $params = array();
      $params[] = array(3);
      $params[] = array(($value['product_quantity'] + $prodIdsCount[$value['product_id']]));
      $conds = array();
      $conds[] = array(0);
      $conds[] = array(0);
      $conds[] = array($value['product_id']);
      $query = $db->db_update("product", $params, $conds);
      $queries[] .= $query.";";
      if($revert_product) {
        $result = $db->database->query($query);
      }
    }

    //UPDATE Bill status
    $params = array();
    $params[] = array(3);
    $params[] = array("expired");
    $conds = array();
    $conds[] = array(0);
    $conds[] = array(0);
    $conds[] = array($billIds[$i]);
    $query = $db->db_update("bill", $params, $conds);
    $queries[] .= $query.";";
    if($update_bill) {
      $result = $db->database->query($query);
    }
  }
/*
  echo "<br />";
  echo "<pre>";
  print_r($queries);
  print_r($billIds);
  print_r($dealIds);
  echo "</pre>";
*/
  return TRUE;
}

function cancel_bill($db, $bill_id) {

  // if (!is_array($bill_id)) {
    // return FALSE;
  // }
  // if (!empty($bill_id)) {
    // return FALSE;
  // }

  $billIds = array();
  $dealIds = array();
  
  //validate bill
  //construct SELECT query
  for ($i=0; $i<count($bill_id); $i++) {
  $cols = array();
  $cols = array(0, 15);
  $conds = array();
  $conds[] = array(3, 3, 0);
  $conds[] = array(6, 6, 0);
  $conds[] = array("new", "pending", $bill_id[$i]);
  $conds[] = array(9,8);
  $query = $db->db_select("bill", $cols, $conds);  
  $queries[] .= $query.";";
  //execute SELECT query
  $result = $db->database->query($query);
  //result SELECT query
  $tmpBill = $result->fetchAll(SQLITE_ASSOC);

  if (empty($tmpBill)) {
    return FALSE;
  }

  $billIds[] = $tmpBill[0]['bill_id'];
  $dealIds[] = $tmpBill[0]['deal_id']; 
  }
  
  print_r($queries);
  
  //revert product quantity
  //revert_product_quantity($db, $dealIds, $billIds);
}

function revert_product_quantity($db, $dealIds, $billIds) {

  $revert_product = TRUE;
  $update_bill = TRUE;

  for ($i=0; $i<count($dealIds); $i++) {
    //Get Deal
    $cols = NULL;
    $conds = array();
    $conds[] = array(0);
    $conds[] = array(0);
    $conds[] = array($dealIds[$i]);
    $query = $db->db_select("deal", $cols, $conds);
    $queries[] .= $query.";";
    $result = $db->database->query($query);
    $tmpDeal = $result->fetchAll(SQLITE_ASSOC);

    //Get Product2Deal
    $cols = NULL;
    $conds = array();
    $conds[] = array(2);
    $conds[] = array(0);
    $conds[] = array($tmpDeal[0]['deal_id']);
    $query = $db->db_select("product2deal", $cols, $conds);
    $queries[] .= $query.";";
    $result = $db->database->query($query);
    $tmpProd2Deal = $result->fetchAll(SQLITE_ASSOC);

    //Construct Temp BAG
    $prodIds = array();
    foreach ($tmpProd2Deal as $value) {
      $prodIds[] = $value["product_id"];
    }
    sort($prodIds);
    $prodIdsUnique = array_unique($prodIds);
    $prodIdsCount = array_count_values($prodIds);

    //Construct Temp PRODUCT
    $prodIdsUniqueStr = implode(",", $prodIdsUnique);
    $query = "SELECT * FROM product WHERE product_id in (".$prodIdsUniqueStr.")";
    $queries[] .= $query.";";
    $result = $db->database->query($query);
    $tmpProd = $result->fetchAll(SQLITE_ASSOC);

    //REVERT Product_quantity
    foreach($tmpProd as $value) {
      $params = array();
      $params[] = array(3);
      $params[] = array(($value['product_quantity'] + $prodIdsCount[$value['product_id']]));
      $conds = array();
      $conds[] = array(0);
      $conds[] = array(0);
      $conds[] = array($value['product_id']);
      $query = $db->db_update("product", $params, $conds);
      $queries[] .= $query.";";
      if($revert_product) {
        $result = $db->database->query($query);
      }
    }

    //UPDATE Bill status
    $params = array();
    $params[] = array(3);
    $params[] = array("expired");
    $conds = array();
    $conds[] = array(0);
    $conds[] = array(0);
    $conds[] = array($billIds[$i]);
    $query = $db->db_update("bill", $params, $conds);
    $queries[] .= $query.";";
    if($update_bill) {
      $result = $db->database->query($query);
    }
  }
/*
  echo "<br />";
  echo "<pre>";
  print_r($queries);
  print_r($billIds);
  print_r($dealIds);
  echo "</pre>";
*/
  return TRUE;
}

function post_request($url, $data, $referer='') {

    // Convert the data array into URL Parameters like a=b&foo=bar etc.
    $data = http_build_query($data);

    // parse the given URL
    $url = parse_url($url);

    if ($url['scheme'] != 'http') {
        die('Error: Only HTTP request are supported !');
    }

    // extract host and path:
    $host = $url['host'];
    $path = $url['path'];

    // open a socket connection on port 80 - timeout: 30 sec
    $fp = fsockopen($host, 80, $errno, $errstr, 30);

    if ($fp){

        // send the request headers:
        fputs($fp, "POST $path HTTP/1.1\r\n");
        fputs($fp, "Host: $host\r\n");

        if ($referer != '')
            fputs($fp, "Referer: $referer\r\n");

        fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
        fputs($fp, "Content-length: ". strlen($data) ."\r\n");
        fputs($fp, "Connection: close\r\n\r\n");
        fputs($fp, $data);

        $result = '';
        while(!feof($fp)) {
            // receive the results of the request
            $result .= fgets($fp, 128);
        }
    }
    else {
        return array(
            'status' => 'err',
            'error' => "$errstr ($errno)"
        );
    }

    // close the socket connection:
    fclose($fp);

    // split the result header from the content
    $result = explode("\r\n\r\n", $result, 2);

    $header = isset($result[0]) ? $result[0] : '';
    $content = isset($result[1]) ? $result[1] : '';

    // return as structured array:
    return array(
        'status' => 'ok',
        'header' => $header,
        'content' => $content
    );
}

function printOrderTable($tmpAddr, $tmpCust, $tmpProd, $tmpPostg, $tmpProdCount) {
  echo "\n";
?>
          <div class="row">
            <div class="span2">
              <h4>BILL TO:</h4>
              <p>
              <address>
                <strong><?php echo $tmpAddr[0]['address_fullname']; ?></strong><br />
                <abbr title="E-mail">E:</abbr><?php echo $tmpCust[0]['customer_email']; ?><br />
              </address>
              </p>
            </div>
            <div class="span2">
              &nbsp;
            </div>
            <div class="span2">
              <h4>SHIP TO:</h4>
              <p>
              <address>
                <strong><?php echo $tmpAddr[0]['address_fullname']; ?></strong><br />
                <?php echo $tmpAddr[0]['address_line1']; ?><br />
                <?php if ($tmpAddr[0]['address_line2'] != "") { ?>
                <?php echo $tmpAddr[0]['address_line2']; ?><br />
                <?php }?>
                <?php echo $tmpAddr[0]['address_city']; ?> <?php echo $tmpAddr[0]['address_region']; ?><br />
                <?php echo $tmpAddr[0]['address_country']; ?><br />
                <abbr title="Postcode">#:</abbr> <?php echo $tmpAddr[0]['address_postcode']; ?><br />
                <abbr title="Phone">P:</abbr> <?php echo $tmpAddr[0]['address_phone']; ?><br />
              </address>
              </p>
            </div>
          </div>
          <table class="table table-striped table-bordered table-condensed">
            <thead>
              <tr>
                <th style="text-align: left;">Product</th>
                <th style="text-align: center;">Quantity</th>
                <th style="text-align: right;">Unit Price</th>
                <th style="text-align: right;">Price</th>
              </tr>
            </thead>
            <tbody>
<?php
        foreach($tmpProd as $value) {
          $prodsPrice[$value['product_id']] = $tmpProdCount[$value['product_id']] * $value['product_price'];
?>
              <tr>
                <td><?php echo $value['product_name']; ?></td>
                <td style="text-align: center;"><?php echo $tmpProdCount[$value['product_id']]; ?></td>
                <td style="text-align: right;"><?php printf("%01.2f", $value['product_price']); ?></td>
                <td style="text-align: right;"><?php printf("%01.2f", $prodsPrice[$value['product_id']]); ?></td>
              </tr>
<?php
        }
        if (isset($prodsPrice)) {
          $totPrice = array_sum($prodsPrice);
        } else {
          $totPrice = 0;
        }
?>
              <tr>
                <td colspan="3">Postage to <?php echo $tmpPostg[0]['postage_country_name']; ?> (by Pos Malaysia)</td>
                <td style="text-align: right;"><?php printf("%01.2f", $tmpPostg[0]['postage_country_price']); ?></td>
              </tr>
              <tr>
                <td colspan="3"><strong>TOTAL</strong></td>
                <td style="text-align: right;"><?php printf("%01.2f", ($totPrice + $tmpPostg[0]['postage_country_price'])); ?></td>
              </tr>
            </tbody>
          </table>
<?php
  echo "\n";
}

function printAlert($alert_type, $alert_heading, $alert_message, $alert_href){

  switch ($alert_type) {
    case "warning":
      $alert_type = "alert-warning";
      $alert_heading_msg = "Warning!";
      break;
    case "error":
      $alert_type = "alert-error";
      $alert_heading_msg = "Error!";
      break;
    case "success":
      $alert_type = "alert-success";
      $alert_heading_msg = "Success!";
      break;
    case "info":
      $alert_type = "alert-info";
      $alert_heading_msg = "Info!";
      break;
  }
?>
          <div class="alert alert-block <?php echo $alert_type;?>">
            <a class="close" data-dismiss="alert" href="<?php echo $_SERVER['PHP_SELF']; ?>">&times;</a>
  <?php if ($alert_heading == NULL) {?>
            <h4 class="alert-heading"><?php echo $alert_heading_msg; ?></h4>
  <?php } else { ?>
            <h4 class="alert-heading"><?php echo $alert_heading; ?></h4>
  <?php } ?>
            <p><?php echo $alert_message; ?></p>
  <?php if ($alert_href != "#") {?>
            <p><a href="<?php echo $alert_href; ?>" class="btn btn-mini btn-info">Back</a></p>
  <?php } ?>
          </div>
<?php
}

function printContinueShopping($href){
?>
          <a class="btn btn-primary btn-default" href="<?php echo $href; ?>"><i class="icon-home icon-white"></i> Continue Shopping</a>
<?php
}

function printPayOnline($href){
?>
          <a class="btn btn-info btn-default" href="<?php echo $href; ?>"><i class="icon-print icon-white"></i> Pay</a>
<?php
}

function printPayOffline($href){
?>
          <a class="btn btn-default btn-default" href="<?php echo $href; ?>"><i class="icon-info-sign icon-default"></i> Learn</a>
<?php
}

function printTimeZone(){
  echo "\n";
?>
          <abbr title="(UTC+08:00) Kuala Lumpur, Singapore"><i class="icon-time"></i></abbr>
<?php
  echo "\n";
}

function pageRedirect($url){
?>
          <script type="text/javascript">
          <!--
          window.location = "<?php echo $url; ?>"
          //-->
          </script>
<?php
}
?>